from fastapi import APIRouter, Body
from fastapi.responses import Response, JSONResponse
from app.services.tools_service import ToolsService
from typing import Optional
import qrcode
import io

router = APIRouter()

@router.post(
    "/qrcode",
    response_class=Response,
    summary="生成二维码",
    description="生成自定义二维码图片"
)
async def generate_qrcode(
    content: str = Body(..., description="二维码内容"),
    size: int = Body(10, description="二维码大小"),
    fill_color: str = Body("#000000", description="前景色"),
    back_color: str = Body("#FFFFFF", description="背景色")
):
    try:
        options = {
            "size": size,
            "fill_color": fill_color,
            "back_color": back_color
        }
        result = ToolsService.generate_qrcode(content, options)
        return Response(
            content=result,
            media_type="image/png"
        )
    except Exception as e:
        return JSONResponse(
            status_code=400,
            content={"message": str(e)}
        )

@router.post(
    "/text/process",
    summary="文本处理",
    description="文本格式化、转换等处理"
)
async def process_text(
    text: str = Body(..., description="待处理文本"),
    operation: str = Body(..., description="处理操作(upper/lower/capitalize/title)")
):
    try:
        result = ToolsService.process_text(text, operation)
        return {
            "code": 200,
            "message": "success",
            "data": result
        }
    except ValueError as e:
        return JSONResponse(
            status_code=400,
            content={"message": str(e)}
        )
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={"message": "处理失败"}
        ) 